package com.it.smartoldb.service;

import com.it.smartoldb.entity.Elderly;
import com.it.smartoldb.repository.ElderlyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 老人管理服务类
 */
@Service
@Transactional
public class ElderlyService {

    @Autowired
    private ElderlyRepository elderlyRepository;

    /**
     * 创建老人信息
     */
    public Elderly createElderly(Elderly elderly) {
        // 检查身份证号是否已存在
        if (elderly.getIdCard() != null && elderlyRepository.findByIdCard(elderly.getIdCard()) != null) {
            throw new RuntimeException("身份证号已存在");
        }
        return elderlyRepository.save(elderly);
    }

    /**
     * 更新老人信息
     */
    public Elderly updateElderly(Long id, Elderly elderly) {
        Optional<Elderly> existing = elderlyRepository.findById(id);
        if (existing.isEmpty()) {
            throw new RuntimeException("老人信息不存在");
        }
        
        // 检查身份证号是否被其他人使用
        Elderly existingElderly = existing.get();
        if (elderly.getIdCard() != null && !existingElderly.getIdCard().equals(elderly.getIdCard())) {
            Elderly duplicateElderly = elderlyRepository.findByIdCard(elderly.getIdCard());
            if (duplicateElderly != null && !duplicateElderly.getId().equals(id)) {
                throw new RuntimeException("身份证号已被其他人使用");
            }
        }
        
        elderly.setId(id);
        return elderlyRepository.save(elderly);
    }

    /**
     * 删除老人信息
     */
    public void deleteElderly(Long id) {
        if (!elderlyRepository.existsById(id)) {
            throw new RuntimeException("老人信息不存在");
        }
        elderlyRepository.deleteById(id);
    }

    /**
     * 根据ID查找老人信息
     */
    public Elderly findById(Long id) {
        return elderlyRepository.findById(id).orElse(null);
    }

    /**
     * 根据身份证号查找老人信息
     */
    public Elderly findByIdCard(String idCard) {
        return elderlyRepository.findByIdCard(idCard);
    }

    /**
     * 根据用户ID查找老人信息
     */
    public Elderly findByUserId(Long userId) {
        System.out.println("ElderlyService.findByUserId - 查询用户ID: " + userId);
        Elderly result = elderlyRepository.findByUserId(userId);
        System.out.println("ElderlyService.findByUserId - 查询结果: " + (result != null ? result.getName() : "null"));
        return result;
    }

    /**
     * 分页查询老人信息
     */
    public Page<Elderly> findAll(int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        return elderlyRepository.findAll(pageable);
    }

    /**
     * 根据姓名模糊查询
     */
    public Page<Elderly> findByNameContaining(String name, int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        return elderlyRepository.findByNameContaining(name, pageable);
    }

    /**
     * 根据状态查询
     */
    public Page<Elderly> findByStatus(String status, int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        return elderlyRepository.findByStatus(status, pageable);
    }

    /**
     * 根据护理级别查询
     */
    public Page<Elderly> findByCareLevel(String careLevel, int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        return elderlyRepository.findByCareLevel(careLevel, pageable);
    }

    /**
     * 复合条件查询
     */
    public Page<Elderly> findByConditions(String name, String idCard, String status, int current, int size) {
        Pageable pageable = PageRequest.of(current - 1, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        return elderlyRepository.findByConditions(name, idCard, status, pageable);
    }

    /**
     * 根据房间号查找
     */
    public List<Elderly> findByRoomNumber(String roomNumber) {
        return elderlyRepository.findByRoomNumber(roomNumber);
    }

    /**
     * 获取所有老人总数
     */
    public long getTotalCount() {
        return elderlyRepository.count();
    }

    /**
     * 获取需要重点关注的老人（健康状态为危险或病重）
     */
    public List<Elderly> getHighRiskElderly() {
        // 这里可以根据实际的健康状态值进行查询
        // 暂时返回所有状态不是 "GOOD" 的老人
        Pageable pageable = PageRequest.of(0, 100);
        return elderlyRepository.findAll(pageable).getContent()
                .stream()
                .filter(elderly -> elderly.getHealthStatus() != null && 
                        !elderly.getHealthStatus().equals("GOOD"))
                .toList();
    }
} 